package com.mingzhi.forum.controller;

import com.mingzhi.forum.common.AppResult;
import com.mingzhi.forum.common.ResultCode;
import com.mingzhi.forum.config.AppConfig;
import com.mingzhi.forum.exception.ApplicationException;
import com.mingzhi.forum.model.Article;
import com.mingzhi.forum.model.Board;
import com.mingzhi.forum.model.User;
import com.mingzhi.forum.service.IArticleService;
import com.mingzhi.forum.service.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Tag(name = "文章接口API")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    /**
     * 发布一个新帖
     *
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @Operation(summary = "发新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @Parameter(description = "帖子id") @RequestParam("boardId") @NonNull Long boardId,
                            @Parameter(description = "标题") @RequestParam("title") @NonNull String title,
                            @Parameter(description = "内容") @RequestParam("content") @NonNull String content) {
        //判断用户是否禁言
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            //表示用户被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //校验板块
        Board board = boardService.selectById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //封装文章对象
        Article createArticle = new Article();
        createArticle.setBoardId(boardId);
        createArticle.setUserId(user.getId());
        createArticle.setTitle(title);
        createArticle.setContent(content);
        //调用service层
        articleService.create(createArticle);

        //响应成功
        return AppResult.success();
    }

    @Operation(summary = "根据板块ID查询帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@Parameter(description = "板块ID") @RequestParam(value = "boardId", required = false) Long boardId) {
        //定义返回的对象
        List<Article> ret = null;
        //进行非空校验
        if (boardId == null) {
            //表示查询的是首页
            ret = articleService.selectAll();
            //打印日志
            log.info("查询所有的帖子");
        } else {
            ret = articleService.selectByBoardId(boardId);
            //打印日志
            log.info("查询板块帖子,boradId = " + boardId);
        }
        //如果为null返回一个空的JSON
        if (ret == null) {
            ret = new ArrayList<>();
        }
        //返回结果
        return AppResult.success(ret);
    }

    @Operation(summary = "根据id查询帖子详情")
    @GetMapping("/getDetails")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id) {
        //从session中获取对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Article article = articleService.selectDetailById(id);
        if (article == null) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //判断当前用户是否为作者
        if (user.getId() == article.getUserId()) {
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @Operation(summary = "编辑帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id,
                            @Parameter(description = "帖子标题") @RequestParam("title") @NonNull String title,
                            @Parameter(description = "帖子内容") @RequestParam("content") @NonNull String content) {
        //从session里面获取用户信息，进而判断用户是否被禁言，是否是管理员
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //查询用户
        Article article = articleService.selectById(id);
        if (article == null) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断用户是不是作者
        if (article.getUserId() != user.getId()) {
            //打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN));
        }
        //判断帖子的状态
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //调用service层
        articleService.modify(id, title, content);
        log.info("更新帖子成功, id = " + id + ", title = " + title + ", content = " + content);
        return AppResult.success();
    }

    @Operation(summary = "帖子点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id) {
        //从session中获取对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if (user.getDeleteState() != 0) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //更新点赞数
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    /**
     * 根据帖子id删除帖子
     *
     * @param id 帖子id
     * @return
     */
    @Operation(summary = "删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id) {
        //根据session 获取用户信息
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        //判断用户是否为禁言状态
        if (user.getState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //根据帖子id查询帖子
        Article article = articleService.selectById(id);
        //判断帖子是否存在或者删除
        if (article == null || article.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断是否为作者
        if (article.getUserId() != user.getId()) {
            //打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用service层 执行删除
        articleService.deleteById(id);
        return AppResult.success();
    }

    @Operation(summary = "根据用户id查询该用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @Parameter(description = "用户id") @RequestParam(value = "userId",required = false) Long userId) {
        if(userId == null){
            //获取session
            User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //调用service
        List<Article> result = articleService.selectByUserId(userId);
        return AppResult.success(result);
    }
}
